package com.moyv.schoolbbs.service;

import android.os.Handler;
import android.util.Log;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.ContentValues.TAG;
import static com.moyv.schoolbbs.config.AccountConstant.TOKEN;
import static com.moyv.schoolbbs.config.URLConstant.STAR_URL;
import static com.moyv.schoolbbs.util.HttpUtil.createClient;

/**
 * @author moyv
 */
public class StarService {
    public void pushStar(int postId, Handler handler, int type, int index) {
        String url = STAR_URL;
        OkHttpClient okHttpClient = createClient();
//        请求体
        JSONObject object = new JSONObject();
        try {
            object.put("postId", postId);
            object.put("type", type);
        } catch (JSONException e) {
            Log.d(TAG, "pushCmt: json操作有问题");
        }


        FormBody formBody = new FormBody.Builder()
                .add("star", object.toString())
                .add("token", TOKEN)
                .build();
//        发送请求操作
        Request request = new Request.Builder()
                .post(formBody)
                .url(url)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                handler.sendMessage(handler.obtainMessage(404));
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String responseData = response.body().string();
                int result = -1;
                try {
                    JSONObject objResponse = new JSONObject(responseData);
                    result = objResponse.getInt("result");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                System.out.println(responseData);
                if (1 == result) {
                    handler.sendMessage(handler.obtainMessage(200, index));
                } else if (2 == result) {
                    handler.sendMessage(handler.obtainMessage(201, index));
                } else if (3 == result) {
                    handler.sendMessage(handler.obtainMessage(302));
                } else {
                    handler.sendMessage(handler.obtainMessage(302));
                }
            }
        });
    }
}
